<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 广告模型
 * 
 * @desc 
 * @version 1.0.0 
 * @author  Jason
 * @date    2017年5月2日 上午11:07:59
 */
class Mod_advertisement extends MY_Model
{
	protected $table_mapper = [
			'master' => 'ad',
			'position'   => 'ad_position',
	];
	
	protected $allowed_fields = [
			'master' => ['position_id', 'name', 'image', 'begin_time', 'end_time', 
				'sort_order', 'status', 'url', 'resource_type', 'resource_id', 'member_id'],
			'position' => ['type', 'name', 'width', 'height', 'member_id'],
	];
	
	use models\common\BinaryBitBasedStatus;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->load->database();
		
		$this->status_bit_config = [
				'master' => [
						// 状态：0不显示1显示
						'status_bit_length' => 1,
						'status_bit_positive_tags' => ['enabled'],
						'status_bit_negative_tags' => ['disabled'],
				],
		];
	}
	
	/**
	 * 插入前处理器
	 *
	 * @desc  主要负责格式化一些字段
	 * @param array  $data
	 * @param string $mapping	表映射
	 *
	 * @return array
	 */
	public function before_create_data_handler($data, $mapping = 'master')
	{
		if ($mapping == 'master') {
			if (!empty($data['begin_time'])) {
				$data['begin_time'] = strtotime($data['begin_time']);
			}
			if (!empty($data['end_time'])) {
				$data['end_time'] = strtotime($data['end_time']);
			}
		}
		
		return $data;
	}
	
	/**
	 * 更新前处理器
	 *
	 * @desc  主要负责格式化一些字段 & 过滤掉多语言字段，确保只在默认语言下更改主表的多语言字段
	 * @param number $id
	 * @param array  $data
	 * @param string $mapping	表映射
	 *
	 * @return array
	 */
	public function before_update_data_handler($id, $data, $mapping = 'master')
	{
		$data = $this->before_create_data_handler($data, $mapping);
		
		return $data;
	}
	
	public function get_ads_by_position($position_id, $limit = null)
	{
		$result = $this->db
						->where('position_id', $position_id)
						->where(['status' => '1'])
						->order_by('sort_order', 'DESC')
						->get($this->table_mapper['master'])
						->result_array();
		
		return $result;
	}
	
}